package com.adcc.monitoragent.show.receive.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.log4j.PropertyConfigurator;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adcc.monitoragent.mina.CharsetCodecFactoryForUDP;
import com.adcc.monitoragent.mina.IoHandlerUDP;
import com.adcc.monitoragent.mina.MinaListener;
import com.adcc.monitoragent.show.receive.MessageReceive;
import com.adcc.monitoragent.util.ProtertiesUtil;

/**
 * 链接层广播服务器端
 * 
 * @author charlie
 * 
 */
public class BroadcastReceive extends MessageReceive {
	private final static Logger log = LoggerFactory
			.getLogger(BroadcastReceive.class);
	private NioDatagramAcceptor acceptor;
	private IoHandlerUDP ioHandler = new IoHandlerUDP();
	private static BroadcastReceive udp = new BroadcastReceive();
    private int port;
    
	private BroadcastReceive() {
	}
	
	public static BroadcastReceive getInstence() {
		return udp;
	}
	@Override
	public boolean connect(int port) {
		this.port = port;
		// 创建非阻塞的server端的UDP连接
		acceptor = new NioDatagramAcceptor();
		DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
		// 添加编码过滤器 处理乱码、编码问题
		filterChain.addLast("codec", new ProtocolCodecFilter(
				new CharsetCodecFactoryForUDP()));

		//字符处理线程池设置
		filterChain.addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));  
		//mina端口复用
		acceptor.getSessionConfig().setReuseAddress(true);
		// 设置核心消息业务处理器
		acceptor.setHandler(ioHandler);
		// 设置session配置，30秒内无操作进入空闲状态
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
		DatagramSessionConfig dcfg = acceptor.getSessionConfig(); 
		dcfg.setReadBufferSize(50000);// 设置接收最大字节默认2048  
		dcfg.setMinReadBufferSize(20000);
        dcfg.setMaxReadBufferSize(50000);  
        dcfg.setReceiveBufferSize(20000);// 设置输入缓冲区的大小  
        dcfg.setSendBufferSize(20000);// 设置输出缓冲区的大小
        dcfg.setReuseAddress(true);// 设置每一个非主监听连接的端口可以重用  
		try {
			// 绑定端口
			acceptor.bind(new InetSocketAddress(port));
		} catch (IOException e) {
			log.error("端口绑定失败" + this.port + e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 添加UdpListener方法
	 */
	public void addListener(MinaListener listener) {
		ioHandler.addListener(listener);
	}

	public static void main(String[] args) {
		// 加载日志配置
		PropertyConfigurator.configure(System.getProperty("user.dir")
				+ "/conf/log4j.properties");
		BroadcastReceive server = new BroadcastReceive();
		class MyListener implements MinaListener {

			@Override
			public void receive(Object msg) {
				log.info(msg.toString());
			}

		}
		server.addListener(new MyListener());
		ProtertiesUtil.init();
		server.connect(ProtertiesUtil.getConfig().getInt("recivePort"));
		log.info("udp接收创建成功" + ProtertiesUtil.getConfig().getInt("recivePort"));
	}
}
